import { getFile } from "@/lib/api/fileController";
import { useEffect, useState, type Dispatch, type SetStateAction } from "react";
import { getPluginsForFile } from "@/lib/plugins/registry";
import client from "@/lib/api/client"
import type { FileInfo } from "@/lib/api/types";

type PreviewFileProps = {
  filePath: string
  setPreviewFile: Dispatch<SetStateAction<{
    path: string
    name: string
  } | null>>
  className?: string
};


export default function PreviewFile({ filePath, setPreviewFile }: PreviewFileProps) {
  const [fileInfo, setFileInfo] = useState<FileInfo>({} as FileInfo)

  const [content, setContent] = useState<string>("")
  const plugin = getPluginsForFile(filePath)

  useEffect(() => {
    getFile({ fileName: filePath }).then(res => {
      setFileInfo(res.fileInfo)
    }).catch(err => {
      console.error(err)
    })


    client.post("/api/text-preview/ReadTextFile", { fileName: filePath }).then(res => {
      setContent(res.data.content)
    }).catch(err => {
      console.error(err)
    })

  }, [])

  return <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 select-text">
    <div className="bg-white p-4 rounded shadow-lg max-w-4xl w-full h-[70vh]">
      <h2 className="text-lg font-bold mb-2">{fileInfo.name}</h2>
      <div className="w-full h-[calc(70vh-100px)] border">
        {/* <TextPreview fileName={filePath} /> */}
        {plugin && plugin.render && plugin.render(content)}
      </div>
      <div className="text-right mt-2">
        <button
          onClick={() => setPreviewFile(null)}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
}
